/**
 * Created by singemazuo on 1/30/16.
 */

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var sha1 = require('sha1');

var db = mongoose.createConnection('localhost','GoodHome');

db.on('error',console.error.bind(console,'连接错误'));

var AuthorizedSchema = new Schema({
    phone:String,
    password:String,
    mail:String,
});

var Authorized = db.model('Authorized',AuthorizedSchema);
module.exports = Authorized;

module.exports.valid = function (auth,callback) {
    var photo = new Buffer(auth.phone,'utf8');
    var password = new Buffer(auth.password,'utf8');

    var _auth = new Authorized();
    _auth.phone = sha1(photo);
    _auth.password = sha1(password);

    Authorized.findOne(_auth,function(err){
        if (err){
            callback(err);
        }else{
            callback();
        }
    });
};

module.exports.add = function (auth,callback) {
    var photo = new Buffer(auth.phone,'utf8');
    var password = new Buffer(auth.password,'utf8');

    var _auth = new Authorized();
    _auth.phone = sha1(photo);
    _auth.password = sha1(password);
    _auth.save(function(err){
        if (err){
            callback(err);
        }else{
            callback(null);
        }
    });
};

